package main

import (
	"fmt"
	"log"
	"strings"
)

/*
	这个文件主要用于对指令进行处理
*/

// 预加载
func preLoading() {
	if fileExists("api_map.json") {
		var err error
		apiMap, err = loadJson("./api_map.json")
		if err != nil {
			log.Fatalf(Red + "Failed to load the file: " + err.Error() + Reset)
		}
	}
}

// 加载基础api文档
func handleBase(cmd *Cmd) {
	// 判断是否为json文件
	if isJson(cmd.base) {

		// 如果已经存在提醒先进行释放
		if fileExists("api_map.json") {
			log.Fatalf(Red + "Please release firt" + Reset)
		}
		fmt.Print(Green + "successful loading json file...\n" + Reset)
		var err error
		LoadFile(cmd.base)
		if err != nil {
			log.Fatalf(Red + "Failed to load the file: " + err.Error() + Reset)
		}
	}
}

// 展示所有api
func handleShow() {
	if apiMap == nil {
		log.Fatalf(Red + "Please select the basic openapi file first" + Reset)
	}
	for key, tags := range apiMap {
		if key == "jsonPath" {
			continue
		}
		fmt.Printf(Yellow+"%s: %v\n"+Reset, key, tags)
	}
}

// 释放api基础文档
func handleRelease() {
	if fileExists("api_map.json") {
		err := deleteFile("api_map.json")
		if err != nil {
			return
		}
		fmt.Println(Green + "File deletion succeeded" + Reset)
	} else {
		log.Fatalf(Red + "File not found" + Reset)
	}
}

func handleStore(tag, apiPath string) {
	// 模糊搜索结果
	filteredAPIs := fuzzySearch(apiPath, apiMap)
	apiSli := []string{}
	// 打印模糊搜索结果
	for k, v := range filteredAPIs {
		if k == "jsonPath" {
			continue
		}
		apiSli = append(apiSli, k)
		fmt.Printf(Yellow+"%s: %v\n"+Reset, k, v)
	}
	if len(filteredAPIs) == 0 {
		return
	}
	fmt.Println()
	var input string
	fmt.Print("Do you want to add these pending API changes to your temporary JSON file? (y/n): ")
	fmt.Scanln(&input)
	if strings.ToLower(input) == "y" {
		err := saveToJson(tag, apiSli, "Temporary_api.json")
		if err != nil {
			return
		}
		fmt.Println(Green + "Successful addition." + Reset)
	} else {
		log.Fatalf(Red + "Operation canceled. APIs not saved." + Reset)
	}
}

func handleFlush() {
	midMap := getTmpInfo()
	// todo 修改为base指定的路径
	fp := getFP()
	fillJson(midMap, fp)
}

func handleDel() {
	midMap := getTmpInfo()
	fp := getFP()
	delJson(midMap, fp)
}
